package com.mesmileAI.controller;

import com.mesmileAI.entity.OderMassage;
import com.mesmileAI.entity.SmileText;
import com.mesmileAI.entity.SmileTransform;
import com.mesmileAI.mapper.SmileTextMapper;
import com.mesmileAI.service.SmileTextService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 文本模型接口
 *
 * <p>
 * --------------------
 *
 * @author  Alexis
 * @since 2020-02-19
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/smileText")
public class SmileTextController  {

    @Resource
    private  SmileTextService smileTextService;

    @Resource
    private SmileTextMapper smileTextMapper;


    /**
     * 详情
     */
    @GetMapping("/detail/{id}")
    public SmileText detail(@PathVariable String id) {
        QueryWrapper<SmileText> smileTextQueryWrapper = new QueryWrapper<>();
        smileTextQueryWrapper.lambda().eq(SmileText::getId,id);
        SmileText detail = smileTextService.getOne(smileTextQueryWrapper);
        //查询用户角色
        if (detail == null) {
           SmileText smileText =new SmileText();
           smileText.setId("500");
            return smileText ;
        }
        return detail ;
    }

    /**
     * 详情
     */
    @GetMapping("/detail/list")
    public List<SmileText> list() {
        //所有list
        List<SmileText> list = smileTextService.list();
        //去除空的list
        List<SmileText> list1 =list.stream().filter(i -> !Objects.equals(i.getLevel(), null) && !Objects.equals(i.getLevel(), "")).toList();
        //排序
        List<SmileText> list2 = new ArrayList<>(list1.stream().sorted(Comparator.comparing(SmileText::getIndexId)).toList());
        //
        list.removeAll(list2);
        list2.addAll(list);
        return list2 ;
    }


    /**
     * 全部列表,只有id，parent_id,name属性 不带文本，chat页面
     */
    @GetMapping("/listByPart")
    public List<SmileText> listByPart(String name) {
        List<SmileTransform> list =smileTextMapper.listNotEdit();
        List<SmileText> smileTexts = new ArrayList<>();
        //存储的list
        List<SmileText> smileTexts1 = new ArrayList<>();
        //给list赋值,复制数据
        list.forEach(i->{
            SmileText smileText = new SmileText();
            smileText.setId(i.getId());
            smileText.setName(i.getName());
            smileText.setIndexId(i.getIndexId());
            smileText.setLevel(i.getLevel());
            smileText.setHierarchy(i.getHierarchy());
            smileTexts.add(smileText);
        });
        if (!Objects.equals(name,null)){
          return smileTextMapper.getByName(name);
        }
        return smileTextService.getChildByOrder(smileTexts).stream().sorted(Comparator.comparing(SmileText::getLevel)).toList();
    }


    /**
     * 返回所有的树状列表,带文本，（排序）
     */
    @GetMapping("/listEdit")
    public List<SmileText> listEditOrder() {
        List<SmileText> list = smileTextService.list();
        return smileTextService.getChildByOrder(list).stream().sorted(Comparator.comparing(SmileText::getLevel)).toList();
    }

    /**
     * 返回所有的数据列表，并且排序，并且除了自己（带文本）(排序)
     */
    @GetMapping("/listExpectSelfOrder/{id}")
    public List<SmileText> listEditOrderSelf(@PathVariable String id) {
        List<SmileText> list = smileTextService.list();
        list.remove(smileTextService.getById(id));
        return smileTextService.getChildByOrder(list);
    }

//    /**
//     * 返回当前去除自己的树状链表
//     */
//    @GetMapping("/listExpectSelf/{id}")
//    public List<SmileText> listExpectSelf(@PathVariable String id){
//        List<SmileText> list = smileTextService.list();
//        List<SmileText> collect = list.stream().filter(i -> Objects.equals(i.getId(), id)).toList();
//        //去除掉相关的的子集id
//        list.removeAll(collect);
//        List<SmileText> parent = smileTextService.getParent(list);
//        List<SmileText> smileTexts = new ArrayList<>();
//        for (SmileText smileText :parent){
//            smileText.setChildren(smileTextService.getChild(smileText,list));
//            smileTexts.add(smileText);
//        }
//        return smileTexts;
//
//    }

//    /**
//     * 返回当前去除自己的树状链表
//     */
//    @GetMapping("/listExpectSelfOrder/{id}")
//    public List<SmileText> listExpectSelfOrder(@PathVariable String id){
//        List<SmileText> list = smileTextService.list();
//        List<SmileText> collect = list.stream().filter(i -> Objects.equals(i.getId(), id)).toList();
//        //去除掉相关的的子集id
//        list.removeAll(collect);
//        List<SmileText> parent = smileTextService.getParent(list);
//        List<SmileText> smileTexts = new ArrayList<>();
//        for (SmileText smileText :parent){
//            smileText.setChildren(smileTextService.getChild(smileText,list));
//            smileTexts.add(smileText);
//        }
//        return smileTexts;
//
//    }

    /**
     * 新增 用户表
     */
    @PutMapping("/save")
    public boolean save(@RequestBody SmileText smileText) {
       try {
           Date date = new Date();
           //创建时间
           smileText.setCreateTime(date);
           //深度
           Integer deep = smileTextService.getDeep(smileText);
           smileText.setHierarchy(deep);
           //从数据库中找出改分级，自动添加level
           if (smileText.getLevel()==99){
           QueryWrapper<SmileText> queryWrapper = new QueryWrapper<>();
           queryWrapper.lambda().eq(SmileText::getIndexId,smileText.getIndexId());
           int count = (int) smileTextService.count(queryWrapper);
           smileText.setLevel(++count);
           }
           //保存数据
           smileTextService.save(smileText);
       }catch (Exception e){
           return false;
       }
       return true;
    }

    /**
     * 修改 用户表
     */
    @PostMapping("/update")
    public boolean update(@RequestBody SmileText smileText) {
        try {
            Date date = new Date();
            smileText.setCreateTime(date);
//            if(smileText.getLevel()==99){
//                smileText.setLevel(Math.toIntExact(smileTextService.lambdaQuery().eq(SmileText::getIndexId, smileText.getIndexId()).count())+1);
//            }
            smileTextService.updateById(smileText);
        }catch (Exception e){
            return false;
        }
        return true;
    }



    /**
     * 删除 用户表
     */
//    @DeleteMapping("/delete")
    @DeleteMapping("/delete/{id}")
    public boolean delete(@PathVariable String id) {
        try {
            smileTextService.removeById(id);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 处理拖拽的接口
     */
    @PostMapping("/orderByOperate")
    public Boolean orderByOperate(@RequestBody OderMassage oderMassage){
        try {

            //从数据库中获取当前对象，不可能为空
            SmileText byId = smileTextService.getById(oderMassage.getId());
            //当拖拽到该一个对象都没有的目录下时
            if (Objects.equals(oderMassage.getNextId(),"")&&Objects.equals(oderMassage.getType(),0)){
                byId.setIndexId(oderMassage.getIndexId());
                SmileText smileTextNext = new SmileText();
                smileTextNext.setIndexId(oderMassage.getIndexId());
                //找到当前层数，并赋值
                byId.setHierarchy(smileTextService.getDeep(smileTextNext));
                //统计该父级下有多id
                byId.setLevel(1);
                smileTextService.updateById(byId);
                return true;
            }
            //获得相邻对象,有可能为空
            SmileText smileText = smileTextService.getById(oderMassage.getNextId());
            //从数据库中获得所有描述对象层级的
            List<SmileText> list= smileTextService.lambdaQuery().eq(SmileText::getIndexId,smileText.getIndexId()).list();
            //判断是否在同一层级
            if (!Objects.equals(byId.getIndexId(),oderMassage.getIndexId())){
                byId.setIndexId(oderMassage.getIndexId());
                byId.setHierarchy(smileText.getHierarchy());
            }
            //统一去掉本身
            list.remove(byId);
            //去掉本身后的排序
            Integer number = smileTextService.getNumber(list, smileText);
            switch (oderMassage.getType()){
                //在描述对象的前面，直接设置描述对象的值，后面的值依次累加
                case 0:{
                    List<SmileText> list1 = smileTextService.setSmileText(list, byId, number);
                    smileTextService.updateBatchById(list1);
                    break;
                }
                //插在后面
                case 1:{
                    List<SmileText> list1 = smileTextService.setSmileText(list, byId, number+1);
                    smileTextService.updateBatchById(list1);
                    break;
                }
                default:{
                    throw new Exception("没有type值！！");
                }
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @GetMapping("/search")
    public List<SmileText> search(String name){
        if (Objects.equals(name,null)||Objects.equals(name,"")){
            List<SmileText> list = smileTextService.list();
            return smileTextService.getChildByOrder(list).stream().sorted(Comparator.comparing(SmileText::getLevel)).toList();
        }
        QueryWrapper<SmileText> smileTextQueryWrapper = new QueryWrapper<>();
        smileTextQueryWrapper.lambda().like(SmileText::getName,name);
        return smileTextService.list(smileTextQueryWrapper).stream().sorted(Comparator.comparing(SmileText::getLevel)).toList();
    }
}